package com.seraph.emailgetter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;

import android.app.ListActivity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;

public class EmailGetter extends ListActivity implements OnItemClickListener {
	
	private static final String IMAGE_STORE_PATH = 
            Environment.getExternalStorageDirectory() + "/DCIM/ShareView";
	private List<Message> m;
	
    /** Called when the activity is first created. */
    @SuppressWarnings("null")
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        m = new ArrayList<Message>();
        	
        List<String> messages = getMail();
        
        getListView().setOnItemClickListener(this);
        
        setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, messages));
    }


	List<String> getMail()
	{
		Properties props=System.getProperties();
	    Session session=Session.getInstance(props,null);
	    props.setProperty("mail.store.protocol", "imaps");
	    
	    Message[] new_msgs = null;
	    Message[] old_msgs = null;
	    
	    Store store = null;
	    Folder inboxfolder = null;
	    
	    try 
	    {
			
	    	store = session.getStore("imaps");
			store.connect("imap.gmail.com","shareview972","somepassword");
			Folder folder = store.getDefaultFolder();
			inboxfolder = folder.getFolder("INBOX");
			inboxfolder.open(Folder.READ_ONLY);
			FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
			new_msgs = inboxfolder.search(ft);
			ft = new FlagTerm(new Flags(Flags.Flag.SEEN), true);
			old_msgs = inboxfolder.search(ft);
		} 
	    catch (NoSuchProviderException e) 
	    {
			Log.i("EMAIL", e.toString());
		} 
	    catch (MessagingException e) 
		{
	    	Log.i("EMAIL", e.toString());
		}
	    
	    List<String> strMsgs = new ArrayList<String>();
	    try
	    {
	    
	        for(int i = 0; i < new_msgs.length; i++)
	        {
	        	m.add(new_msgs[i]);
	        	strMsgs.add(new_msgs[i].getSubject());
	        }
	        
	        for(int i = 0; i < old_msgs.length; i++)
	        {
	        	m.add(old_msgs[i]);
	        	strMsgs.add(old_msgs[i].getSubject());
	        }
	    
	    } 
	    catch (MessagingException e) 
	    {
			// TODO Auto-generated catch block
			Log.i("EMAIL", e.toString());
		}
	    
//	    try 
//	    {
//			inboxfolder.close(false);
//			store.close();
//		} 
//	    catch (MessagingException e) 
//	    {
//	    	Log.i("EMAIL", e.toString());
//		}
	    
	    return strMsgs;
	}
	
	@Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);
        int groupId = 0;
        int menuItemOrder = Menu.NONE;
        // Create menu ids for the event handler to reference
        int menuItemId1 = Menu.FIRST;
        // Create menu text
        int menuItemText1 = R.string.refresh;
        // Add the items to the menu
        MenuItem menuItem1 = menu.add(groupId, menuItemId1, menuItemOrder, menuItemText1);
                //.setIcon(R.drawable.ic_menu_close_clear_cancel);
        return true;
    }
	
	// Handle events from the popup menu above   
    public boolean onOptionsItemSelected(MenuItem item){
        super.onOptionsItemSelected(item);
        switch(item.getItemId()){
            case (Menu.FIRST):
            	List<String> messages = getMail();
            	setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, messages));
                return true;             
        }
        return false;
    }


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		Message message = m.get(arg2);
		
		try {
			Multipart mul = (Multipart)message.getContent();
			
			for (int i = 0; i < mul.getCount(); i++) {
		        BodyPart bodyPart = mul.getBodyPart(i);
		        if(Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition()))
		        {
		        	Log.i("EMAIL", "Attachment present");
		        	InputStream is = bodyPart.getInputStream();
		            File f = new File(bodyPart.getFileName());
		            FileOutputStream fos = new FileOutputStream(f);
		            byte[] buf = new byte[4096];
		            int bytesRead;
		            while((bytesRead = is.read(buf))!=-1) {
		                fos.write(buf, 0, bytesRead);
		            }
		            fos.close();
		            Log.i("EMAIL", "File written");
		            
		            Bitmap pic = BitmapFactory.decodeFile(f.getAbsolutePath());
		            String body = message.getSubject();
		            Log.i("EMAIL", "Got pic and subject");
		            
		            Intent j = new Intent(this, MessageView.class);
		            MessageView.setMessage(body, pic);
		            startActivity(j);
		        }
			}

		} catch (IOException e) {
			// TODO Auto-generated catch block
			Log.i("EMAIL", e.toString());
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			Log.i("EMAIL", e.toString());
		}
	}
	
}